package com.cynen.p42u.task;

import com.cynen.p42u.pojo.JavDict;
import com.cynen.p42u.pojo.JavInfo;
import com.cynen.p42u.pojo.JavLibInfo;
import com.cynen.p42u.service.JavDictService;
import com.cynen.p42u.service.JavLibService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

/**
 * 组合实体类的控制输出.
 *
 * 通过 自定义的输出Pipline,实现自定义处理.
 */

@Component
public class JavInfoPipline implements Pipeline {

    @Autowired
    private JavLibService javLibService;

    @Autowired
    private JavDictService javDictService;

    @Override
    @Transactional
    public void process(ResultItems resultItems, Task task) {
        JavInfo javInfo = resultItems.get("javInfo");
        if (javInfo != null) {
            // 不为空,就需要保存.
            // 保存主影片信息.
            JavLibInfo javLibInfo = javInfo.getJavLibInfo();
            if (javLibInfo != null){
                // 根据 videoID去重.
                JavLibInfo javLibInfo1 = new JavLibInfo();
                javLibInfo1.setVideoId(javLibInfo.getVideoId());
                List all = javLibService.findAll(javLibInfo1);
                if (all.size() > 0) {
                    // 重复,不存.
                    System.out.println(javLibInfo.getVideoId()+ "重复,不存入Info表");
                }else {
                    // 不重复,才保存.
                    javLibService.save(javLibInfo);
                    // 保存相关字典值.
                    List<JavDict> dictList = javInfo.getDictList();
                    if (dictList.size() > 0){
                        for (JavDict dict : dictList){
                            javDictService.save(dict);
                        }
                    }
                }
            }

        }
    }
}
